package com.example.demospringmybatisplus.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demospringmybatisplus.entity.Users;
import com.example.demospringmybatisplus.mapper.UsersMapper;

/**
 * 查询用户列表
 *
 * @author
 * @DATE 2024/9/9
 **/
@Service
public abstract class InsertUserListService implements IService<Users> {

    @Resource
    private UsersMapper usersMapper;

    /**
     * 通过分页查询数据，然后再将分页查询的结果批量进行保存
     * 防止一次性查询数据过大，导致内存溢出
     */
    public void insertUserList() {
        // 分页参数
        int currentPage = 1;
        int pageSize = 3;
        long totalPages;

        do {
            Page<Users> rowPage = new Page<>(currentPage, pageSize);

            // queryWrapper 组装查询 where 条件
            LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
            Page<Users> usersPage = usersMapper.selectPage(rowPage, queryWrapper);

            if (usersPage == null || usersPage.getRecords() == null || usersPage.getRecords().isEmpty()) {
                break;
            }

            this.saveBatch(usersPage.getRecords());

            totalPages = usersPage.getTotal();
            currentPage++;
        } while (currentPage <= totalPages / pageSize);
    }
}
